package name.zxw.datastructures.sparsearray;

import java.util.Arrays;

/**
 * @author ZhangXinWang
 * @date 2022/5/8 13:52
 */
public class SparseArray {

    public static void main(String[] args) {
        //创建一个原始的二维数组11*11
        int chessArr1[][] = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        //展示二维数组
        for (int i = 0; i < chessArr1.length; i++) {
            System.out.println(Arrays.toString(chessArr1[i]));
        }
        System.out.println("------------------------------------------");

        //二维数组转稀疏数组
        int sum = 0;
        for (int i = 0; i < chessArr1.length; i++) {
            for (int j = 0; j < chessArr1[i].length; j++) {
                if (chessArr1[i][j] != 0) {
                    sum++;
                }
            }
        }
        int sparseArr[][] = new int[sum + 1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;
        int count = 0;
        for (int i = 0; i < chessArr1.length; i++) {
            for (int j = 0; j < chessArr1[i].length; j++) {
                if (chessArr1[i][j] != 0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr1[i][j];
                }
            }
        }
        //展示稀疏数组
        for (int i = 0; i < sparseArr.length; i++) {
            System.out.println(Arrays.toString(sparseArr[i]));
        }
        System.out.println("------------------------------------------");

        //稀疏数组转二维数组
        int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 0; i < sparseArr[0][2]; i++) {
            chessArr2[sparseArr[i + 1][0]][sparseArr[i + 1][1]] = sparseArr[i + 1][2];
        }
        //展示二维数组
        for (int i = 0; i < chessArr2.length; i++) {
            System.out.println(Arrays.toString(chessArr2[i]));
        }
        System.out.println("------------------------------------------");


    }


}
